package com.oocl.chatroom.servermanage.requesthandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;

import org.jdom.Element;
import org.json.JSONException;
import org.json.JSONObject;

import com.oocl.chatroom.network.protocol.HttpProtocol;
import com.oocl.chatroom.network.protocol.Message;
import com.oocl.chatroom.server.ChatServer;
import com.oocl.chatroom.server.main.ServerStart;
import com.oocl.chatroom.server.sender.Sender;
import com.oocl.chatroom.servermanage.requestparse.RequestParse;
import com.oocl.chatroom.servermanage.requestparse.impl.RequestParseImpl;
import com.oocl.chatroom.servermanage.response.Response;
import com.oocl.chatroom.servermanage.view.HtmlProducer;

public class HttpRequestHandler implements Runnable{
     private Socket socket;
     private RequestParse parse;
     private Response response;
      
     
	public void setSocket(Socket socket) {
		this.socket = socket;
	}
	public HttpRequestHandler() {
		super();
		parse = new RequestParseImpl();
		
	}

	public void run() {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			OutputStream out = socket.getOutputStream();
			parse.setReader(reader);
			HttpProtocol http = parse.parseRequest();
			response = new Response(out);
			handler(http);
			out.close();
			reader.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private void handler(HttpProtocol http) {
		if(http.getType().equals("GET")){
			
			switch(http.getReqeust()){
			  case "/": toIndex();  break;
			  case "/1": toStart();  break;
			  case "/2": toClose(); break;
			  case "/3": toList(); break;
			  case "/4": toTime(); break;
			  default:break;
			}
			
		}
	}
	private void toTime() {
		Element root = new Element("html");
	    Element body = new Element("body");
	    root.addContent(body);
		Element buttonArea = HtmlProducer.creatIndexPage();
		body.addContent(buttonArea);
		try {
		Message msg = new Message("get nameList", 11, "manage","chatServer", new Date().getTime());
		Socket sock = new Socket("127.0.0.1",8888);
		PrintWriter out = new PrintWriter(sock.getOutputStream());
		JSONObject jOb = new JSONObject(msg);
		String json = jOb.toString();
		out.println(json);
		out.flush();
		 BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
		 String msgJson =  in.readLine();
		 //System.out.println(msgJson);
		 JSONObject jb = new JSONObject(msgJson);
		 String content = jb.getString("content");
		 long startTime = Long.parseLong(content);
		 long time = (new Date().getTime()) - startTime;
		  
			Element h = new Element("h3");
			h.addContent(time+" ms");
			body.addContent(h);
			response.print(root);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			Element h =new Element("h3");
			h.setText("chat Server is closed!");
			body.addContent(h);
			response.print(root);
		}
	}
	private void toList() {
		Element root = new Element("html");
	    Element body = new Element("body");
	    root.addContent(body);
		Element buttonArea = HtmlProducer.creatIndexPage();
		body.addContent(buttonArea);
		try {
			Message msg = new Message("get nameList", 10, "manage","chatServer", new Date().getTime());
			Socket sock = new Socket("127.0.0.1",8888);
			PrintWriter out = new PrintWriter(sock.getOutputStream());
			JSONObject jOb = new JSONObject(msg);
			String json = jOb.toString();
			out.println(json);
			out.flush();
			 BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
			 String msgJson =  in.readLine();
			 //System.out.println(msgJson);
			 JSONObject jb = new JSONObject(msgJson);
			 String content = jb.getString("content");
			 //System.out.println(content);
			 String[] names = content.split(";");
				Element div =HtmlProducer.createListPage(names);
				body.addContent(div);
				response.print(root);
		}catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			Element h =new Element("h3");
			h.setText("chat Server is closed!");
			body.addContent(h);
			response.print(root);
		}
	}
	
	
	
	private void toClose() {
		Socket socket = null;
		Element root = new Element("html");
	    Element body = new Element("body");
	    root.addContent(body);
		Element buttonArea = HtmlProducer.creatIndexPage();
		body.addContent(buttonArea);
		try {
			socket = new Socket("127.0.0.1",8888);
		} catch (UnknownHostException e) {
		} catch (IOException e) {
		}
		if(socket==null){
			Element h = new Element("h3");
			h.addContent("server has  closed!");
			body.addContent(h);
			response.print(root);
		}else{
			try {
				Message msg = new Message("close server", 9, "manage",
						"chatServer", new Date().getTime());
				PrintWriter out = new PrintWriter(socket.getOutputStream());
				JSONObject jOb = new JSONObject(msg);
				String json = jOb.toString();
				out.println(json);
				out.flush();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				Element h = new Element("h3");
				h.addContent("server  closes successfully!");
				body.addContent(h);
				response.print(root);
		}
	}
	private void toStart() {
		Socket socket =null;
		Element root = new Element("html");
	    Element body = new Element("body");
	    root.addContent(body);
		Element buttonArea = HtmlProducer.creatIndexPage();
		int flag=0;
		try {
			//server = new ChatServer(8888);
			 socket = new Socket("127.0.0.1",8888);
			 
		} catch (UnknownHostException e) {
		} catch (IOException e) {
			flag = 1;
			try {
				new Thread(new ServerStart(new ChatServer(8888))).start();
				Element h = new Element("h3");
				h.addContent("server start succefully!");
				body.addContent(buttonArea);
				body.addContent(h);
				response.print(root);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		if(socket!=null&&flag==0){
			Element h = new Element("h3");
			h.addContent("server has  started!");
			body.addContent(buttonArea);
			body.addContent(h);
			response.print(root);
		}else if(socket!=null&&flag==0){
			try {
				new Thread(new ServerStart(new ChatServer(8888))).start();
				Element h = new Element("h3");
				h.addContent("server start succefully!");
				body.addContent(buttonArea);
				body.addContent(h);
				response.print(root);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	private void toIndex() {
		Element root = new Element("html");
	    Element body = new Element("body");
	    root.addContent(body);
		Element buttonArea = HtmlProducer.creatIndexPage();
		body.addContent(buttonArea);
		response.print(root);
	}
}
